import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/layout',
  },

  {
    path: '/layout',
    name: 'Layout',
    component: () => import(/* webpackChunkName: "about" */ '../layouts/index.vue'),
    redirect: '/layout/home',
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import(/* webpackChunkName: "home" */ '../views/Home.vue'),
      },
      {
        path: 'cart',
        name: 'Cart',
        component: () => import(/* webpackChunkName: "cart" */ '../views/Cart.vue'),
      },
    ],
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "about" */ '../views/Login.vue'),
  },
  {
    path: '*',
    name: 'NotFound',
    component: () => import(/* webpackChunkName: "404" */ '../views/404.vue'),
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})

// 导航守卫效果
// router 进入页面的时候，会经过路由
router.beforeEach((to, from, next) => {
  console.log(to, '用户去哪个页面')
  console.log(from, '用户从哪儿来')
  // next 让用户继续往下走
  // 1. 判断用户是不是去的登陆页面。如果是登陆页面，用户直接走下去，
  // 2. 如果不是登陆页面，再判断有没有登陆
  if (to.name === 'Login') {
    next()
  } else {
    // 从vuex中取出token
    const token = store.state.token
    // const token = localStorage.getItem('token')

    if (token) {
      // 有token, 让用户继续访问
      next()
    } else {
      // 没有token,让用户先等再访问
      next({
        path: '/login',
      })
    }
  }
})

export default router
